﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Diagnostics;
using System.Xml;

namespace Senior_Project
{
    public partial class ProfilePage : PhoneApplicationPage
    {
        App app = App.Current as App;

        // set object class
        UserProfile profile, newProfile;

        PageOrientation lastOrientation;      //set "lastOrientation" for detect page orientation
        public ProfilePage()
        {
            InitializeComponent();
            this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(ProfilePage_OrientationChanged);
            lastOrientation = this.Orientation;

            OpenUserProfile();
        }

        //detect and handle page orientation
        void ProfilePage_OrientationChanged(object sender, OrientationChangedEventArgs e)         
        {
            PageOrientation newOrientation = e.Orientation;
            Debug.WriteLine("New orientation: " + newOrientation.ToString());

            RotateTransition transitionElement = new RotateTransition();
            switch (newOrientation)
            {
                case PageOrientation.Landscape:
                case PageOrientation.LandscapeRight:
                    // Come here from PortraitUp (i.e. clockwise) or LandscapeLeft?
                    if (lastOrientation == PageOrientation.PortraitUp)
                        transitionElement.Mode = RotateTransitionMode.In90Counterclockwise;
                    else
                        transitionElement.Mode = RotateTransitionMode.In180Clockwise;
                    break;
                case PageOrientation.LandscapeLeft:
                    // Come here from LandscapeRight or PortraitUp?
                    if (lastOrientation == PageOrientation.LandscapeRight)
                        transitionElement.Mode = RotateTransitionMode.In180Counterclockwise;
                    else
                        transitionElement.Mode = RotateTransitionMode.In90Clockwise;
                    break;
                case PageOrientation.Portrait:
                case PageOrientation.PortraitUp:
                    // Come here from LandscapeLeft or LandscapeRight?
                    if (lastOrientation == PageOrientation.LandscapeLeft)
                        transitionElement.Mode = RotateTransitionMode.In90Counterclockwise;
                    else
                        transitionElement.Mode = RotateTransitionMode.In90Clockwise;
                    break;
                default:
                    break;
            }

            // Execute the transition
            PhoneApplicationPage phoneApplicationPage = (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;
            ITransition transition = transitionElement.GetTransition(phoneApplicationPage);
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();

            lastOrientation = newOrientation;
        }


        public void OpenUserProfile()
        {
            // open userXML.xml file and read data
            string test;
            try
            {
                // set variable refer to IsolatedStorageFile
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // set variable refer to IsolatedStorageFileStream
                    IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("userXML.xml", FileMode.Open);
                    using (StreamReader reader = new StreamReader(isoFileStream))
                    {
                        // read to end file
                        test = reader.ReadToEnd();


                        // set element for feed data from userXML.xml file
                        XElement element = XElement.Parse(test);
                        var items = from item in element.Descendants("user")
                                    select profile = new UserProfile
                                    {
                                        Uid = item.Element("uid").Value,
                                        UserName = item.Element("username").Value,
                                        Password = item.Element("password").Value,
                                        Name = item.Element("name").Value,
                                        Gender = item.Element("gender").Value,
                                        Age = item.Element("age").Value,
                                        Email = item.Element("email").Value,
                                        Birthday = item.Element("birthday").Value,
                                        Blood = item.Element("blood").Value,
                                        Height = item.Element("height").Value,
                                        Weight = item.Element("weight").Value,

                                        Disease = item.Element("disease").Value,
                                        Calorie_Limit = item.Element("calorie_limit").Value,
                                        Protein_Limit = item.Element("protein_limit").Value,
                                        Fat_Limit = item.Element("fat_limit").Value
                                    };

                        // check items
                        int count = items.Count();
                        if (count == 1)
                        {
                            if (profile.Protein_Limit == "" && profile.Fat_Limit == "")
                            {
                                string result = "Name : " + profile.Name + "\n" +
                                                "Gender : " + profile.Gender + "\n" +
                                                "Birthday : " + profile.Birthday + "\n" +
                                                "Age : " + profile.Age + "\n" +
                                                "Blood : " + profile.Blood + "\n" +
                                                "Weight : " + profile.Weight + " kg." + "\n" +
                                                "Height : " + profile.Height + " cm." + "\n" +
                                                "E-mail : " + profile.Email + "\n\n" +
                                                "Nutritional information\n" +
                                                "Disease : " + profile.Disease + "\n" +
                                                "Calory_limit : " + profile.Calorie_Limit + " kcal.";

                                profiletxtblock.Text = result;
                            }
                            if (profile.Calorie_Limit == "" && profile.Fat_Limit == "")
                            {
                                string result = "Name : " + profile.Name + "\n" +
                                                "Gender : " + profile.Gender + "\n" +
                                                "Birthday : " + profile.Birthday + "\n" +
                                                "Age : " + profile.Age + "\n" +
                                                "Blood : " + profile.Blood + "\n" +
                                                "Weight : " + profile.Weight + " kg." + "\n" +
                                                "Height : " + profile.Height + " cm." + "\n" +
                                                "E-mail : " + profile.Email + "\n\n" +
                                                "Nutritional information\n" +
                                                "Disease : " + profile.Disease + "\n" +
                                                "Protein_limit : " + profile.Protein_Limit + " g.";

                                profiletxtblock.Text = result;
                            }
                            if (profile.Calorie_Limit == "" && profile.Protein_Limit == "")
                            {
                                string result = "Name : " + profile.Name + "\n" +
                                                "Gender : " + profile.Gender + "\n" +
                                                "Birthday : " + profile.Birthday + "\n" +
                                                "Age : " + profile.Age + "\n" +
                                                "Blood : " + profile.Blood + "\n" +
                                                "Weight : " + profile.Weight + " kg." + "\n" +
                                                "Height : " + profile.Height + " cm." + "\n" +
                                                "E-mail : " + profile.Email + "\n\n" +
                                                "Nutritional information\n" +
                                                "Disease : " + profile.Disease + "\n" +
                                                "Fat_limit : " + profile.Fat_Limit + " g.";

                                profiletxtblock.Text = result;
                            }
                        }
                        else MessageBox.Show("can not find userXML.xml file");
                    }
                }
            }
            catch { MessageBox.Show("File not found !"); }
        }

        private void syncProfile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // set client
            Random rand = new Random();
            WebClient client = new WebClient();
            client.DownloadStringAsync(new Uri("http://" + app.url + "/tracking/mobile/profile.php?r=" + rand.Next(), UriKind.RelativeOrAbsolute));
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // show error if error != null
                MessageBox.Show(e.Error.Message);
                return;
            }

            // feed xml data from "profile.php" in localhost mode
            XElement element = XElement.Parse(e.Result);
            var items = from item in element.Descendants("user")
                        where item.Element("uid").Value == profile.Uid    // check user ID
                        select newProfile = new UserProfile
                        {
                            //feed value of elements to new UserData class
                            Uid = item.Element("uid").Value,
                            UserName = item.Element("username").Value,
                            Password = item.Element("password").Value,
                            Age = item.Element("age").Value,
                            Name = item.Element("name").Value,
                            Gender = item.Element("gender").Value,
                            Email = item.Element("email").Value,
                            Birthday = item.Element("birthday").Value,
                            Blood = item.Element("blood").Value,
                            Height = item.Element("height").Value,
                            Weight = item.Element("weight").Value,

                            Disease = item.Element("disease").Value,
                            Calorie_Limit = item.Element("cal_limit").Value,
                            Protein_Limit = item.Element("protein_limit").Value,
                            Fat_Limit = item.Element("fat_limit").Value
                        };
            int count = items.Count();     //count items for check username and password

            if (count == 1)
            {
                CreateUser();       // call method "CreateUser" to create xml file
            }
            else MessageBox.Show("Username Invalid. Please try again");
        }

        //******************************** Create xml file for check login [userXML.xml] **************************************
        public void CreateUser()
        {
            // set variable refer to IsolatedStorageFile
            using (IsolatedStorageFile myIsolated = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // set variable refer to IsolatedStorageFileStream
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("userXML.xml", FileMode.Create, FileAccess.Write, myIsolated))
                {
                    // set variable refer to XmlWriterSetting
                    XmlWriterSettings setting = new XmlWriterSettings();
                    setting.Indent = true;

                    // set variable refer to XmlWriter
                    using (XmlWriter writer = XmlWriter.Create(isoStream, setting))
                    {
                        // create element and value
                        writer.WriteStartElement("p", "profile", "upn:profile");

                        writer.WriteStartElement("user");

                        writer.WriteStartElement("uid");
                        writer.WriteString(newProfile.Uid);
                        writer.WriteEndElement();

                        writer.WriteStartElement("username");
                        writer.WriteString(newProfile.UserName);
                        writer.WriteEndElement();

                        writer.WriteStartElement("password");
                        writer.WriteString(newProfile.Password);
                        writer.WriteEndElement();

                        writer.WriteStartElement("age");
                        writer.WriteString(newProfile.Age);
                        writer.WriteEndElement();

                        writer.WriteStartElement("name");
                        writer.WriteString(newProfile.Name);
                        writer.WriteEndElement();

                        writer.WriteStartElement("gender");
                        writer.WriteString(newProfile.Gender);
                        writer.WriteEndElement();

                        writer.WriteStartElement("email");
                        writer.WriteString(newProfile.Email);
                        writer.WriteEndElement();

                        writer.WriteStartElement("birthday");
                        writer.WriteString(newProfile.Birthday);
                        writer.WriteEndElement();

                        writer.WriteStartElement("blood");
                        writer.WriteString(newProfile.Blood);
                        writer.WriteEndElement();

                        writer.WriteStartElement("height");
                        writer.WriteString(newProfile.Height);
                        writer.WriteEndElement();

                        writer.WriteStartElement("weight");
                        writer.WriteString(newProfile.Weight);
                        writer.WriteEndElement();


                        writer.WriteStartElement("disease");
                        writer.WriteString(newProfile.Disease);
                        writer.WriteEndElement();

                        writer.WriteStartElement("calorie_limit");
                        writer.WriteString(newProfile.Calorie_Limit);
                        writer.WriteEndElement();

                        writer.WriteStartElement("protein_limit");
                        writer.WriteString(newProfile.Protein_Limit);
                        writer.WriteEndElement();

                        writer.WriteStartElement("fat_limit");
                        writer.WriteString(newProfile.Fat_Limit);
                        writer.WriteEndElement();

                        writer.WriteEndElement();

                        // end document
                        writer.WriteEndDocument();

                        // writer to file
                        writer.Flush();
                    }
                }
            }

            OpenUserProfile();
        }
        //*************************************************************************************************************
    }
}